package com.learning.spring.cloud.alibaba.sentinel.order.web.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * ClassName: SentinelBlockExceptionHandler
 * Description:
 * Date: 2021/9/4 16:26 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        final HashMap<Object, Object> map = Maps.newHashMap();
        if (e instanceof FlowException) {
            map.put("code", -1);
            map.put("msg", "限流");
        } else if (e instanceof DegradeException) {
            map.put("code", -2);
            map.put("msg", "降级熔断");
        } else if (e instanceof ParamFlowException) {
            map.put("code", -3);
            map.put("msg", "限流");
        } else if (e instanceof SystemBlockException) {
            map.put("code", -4);
            map.put("msg", "系统");
        } else if (e instanceof AuthorityException) {
            map.put("code", -5);
            map.put("msg", "授权");
        }

        response.setStatus(429);
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(map));
        out.flush();
        out.close();
    }
}
